package com.itkm.eurekaprovider.controller;

import com.itkm.eurekaprovider.service.CommentService;
import com.itkm.pojo.Comment;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class CommentController {
    @Value("${spring.application.name}")
    private String appName;
    @Value("${server.port}")
    private String port;
    @Resource
    private CommentService commentService;

    @GetMapping("/comment/all")
    public List<Comment> queryCommentList() {
        return commentService.getComments().stream()
                .peek(comment -> comment.setProvider(appName + "-" + port))
                .collect(Collectors.toList());
    }

    @HystrixCommand(fallbackMethod = "defaultComment")
    @GetMapping("/comment/{id}")
    public Comment queryCommentById(@PathVariable int id) {
        return commentService.getCommentById(id)
                .map(comment -> {
                    comment.setProvider(appName + "-" + port);
                    return comment;
                })
                .orElseThrow(() -> new RuntimeException("未查询到id:" + id + "的评论"));
    }

    public Comment defaultComment(int id) {
        return new Comment(){{
            setId(-1);
            setProvider(appName + "-" + port);
            setContent("未查询到id: " + id + " 的评论");
        }};
    }
}
